package com.example.zhaoping.util;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.zhaoping.entity.Admin;
import com.example.zhaoping.entity.Menu;
import com.example.zhaoping.entity.RefMenu;
import com.example.zhaoping.serviceImpl.AdminServiceImpl;
import com.example.zhaoping.serviceImpl.MenuServiceImpl;
import com.example.zhaoping.serviceImpl.RefMenuServiceImpl;
import io.netty.handler.codec.http.HttpMethod;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.BindException;

@Component
public class Authorization implements HandlerInterceptor {
    private Result result = new Result();
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private RefMenuServiceImpl refMenuService;
    @Autowired
    private MenuServiceImpl menuService;
    @Autowired
    private AdminServiceImpl adminService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        if (token == null ||"".equals(token)) {
            throw new TokenException(401,"未登录,请求前往登录!");
        }
        tokenUtil.checkSign(token);
        int id = TokenUtil.getUserId(token);
        String requestURI = request.getRequestURI();
        Menu menu = menuService.selectByUrl(requestURI);
        String[] urlList = requestURI.split("/");
        Admin admin = adminService.selectAdminById(id);
        //管理员直接通过不用验证权限
        if(menu!=null && !urlList[1].equals("error") && admin == null) {
            QueryWrapper<RefMenu> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(urlList[1] + "_id", id)
                    .eq("menu_url", requestURI);
            RefMenu refMenu = refMenuService.selectOne(queryWrapper);
            if (refMenu == null) {
                throw new TokenException(403,"权限不足!");
            }
        }
        return true;
    }

}
